package com.rongshu.view.submitArticle.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.view.submitArticle.bean.LabelBean;
import com.widget.toast.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * created by zhengweis on 2018/11/1.
 * description：
 */
public class ArticleLabelAdapter extends RecyclerView.Adapter<ArticleLabelAdapter.ViewHolder> {
    private Context context;
    private List<LabelBean> list;

    public ArticleLabelAdapter(Context context, List<LabelBean> list) {
        this.list = list;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_label_rectangle, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
        viewHolder.tag.setText(list.get(i).getTitle());
        viewHolder.tag.setBackgroundResource(list.get(i).getIsSelected() ?
                R.drawable.shape_oval_green_background : R.drawable.shape_oval_gray_background);
        viewHolder.tag.setTextColor(list.get(i).getIsSelected() ?
                ContextCompat.getColor(context, R.color.color_3CC051) : ContextCompat.getColor(context, R.color.color_4a4a4a));
        viewHolder.tag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LabelBean bean = list.get(i);
                bean.setIsSelected(!bean.getIsSelected());//记录item的选择状态
                if (bean.getIsSelected()) {
                    if (getSelectedLabel().size() > 4) {
                        bean.setIsSelected(!bean.getIsSelected());//如果选中的item超过了4条，则不记录当前item的选择状态
                        ToastUtils.show("请最多选中4个标签");
                        return;
                    }
                }
                notifyDataSetChanged();
            }
        });
    }

    private List<LabelBean> getSelectedLabel() {
        List<LabelBean> selectedList = new ArrayList<>();
        for (LabelBean bean : list) {
            if (bean.getIsSelected()) {
                selectedList.add(bean);
            }
        }
        return selectedList;
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tag;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tag = itemView.findViewById(R.id.search_tag);
        }
    }
}
